<template>
  <view class="tool-wrap">
    <input class="ipt" type="text" v-model="text" placeholder="输入文本或链接" placeholder-class="ph" />
    <button class="btn primary" @tap="generate">生成二维码</button>
    <canvas id="qr" canvas-id="qr" class="canvas" ref="qr" v-show="hasQr"></canvas>
    <text class="hint">使用第三方库生成标准二维码。</text>
  </view>
</template>

<script>
/* #ifdef MP-WEIXIN */
import WeappQrcode from 'weapp-qrcode'
/* #endif */
/* #ifdef H5 */
import QRCode from 'qrcode'
/* #endif */
export default {
  name: 'QrcodeGenerator',
  data() {
    return { text: '', hasQr: false }
  },
  mounted() {},
  methods: {
    generate() {
      const value = (this.text || '').trim()
      if (!value) {
        uni.showToast({ title: '请输入内容', icon: 'none' })
        return
      }
      const SIZE = 200
      /* #ifdef MP-WEIXIN */
      try {
        // 正确使用 weapp-qrcode：第一个参数为 canvasId，第三个参数传入组件实例（uni-app）
        new WeappQrcode('qr', {
          text: value,
          width: SIZE,
          height: SIZE,
          // 去除留白，背景改为白色与二维码同尺寸
          padding: 0,
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: WeappQrcode.CorrectLevel && WeappQrcode.CorrectLevel.H ? WeappQrcode.CorrectLevel.H : 3,
        }, this)
        this.hasQr = true
        uni.showToast({ title: '已生成二维码', icon: 'none' })
      } catch (e) {
        uni.showToast({ title: '生成失败', icon: 'none' })
      }
      /* #endif */

      /* #ifdef H5 */
      this.$nextTick(() => {
        const tryRender = (canvasEl) => {
          if (!canvasEl || typeof canvasEl.getContext !== 'function') {
            uni.showToast({ title: '画布不存在', icon: 'none' })
            return
          }
          canvasEl.width = SIZE
          canvasEl.height = SIZE
          // 先铺一层白色背景，大小与二维码一致
          const ctx = canvasEl.getContext('2d')
          if (ctx) {
            ctx.fillStyle = '#ffffff'
            ctx.fillRect(0, 0, SIZE, SIZE)
          }
          QRCode.toCanvas(canvasEl, value, { width: SIZE, margin: 0, errorCorrectionLevel: 'H', color: { dark: '#000000', light: '#ffffff' } })
            .then(() => {
              this.hasQr = true
              uni.showToast({ title: '已生成二维码', icon: 'none' })
            })
            .catch(() => {
              uni.showToast({ title: '生成失败', icon: 'none' })
            })
        }

        // 优先通过 ref 获取
        let canvas = (this.$refs && this.$refs.qr) ? (this.$refs.qr.$el || this.$refs.qr) : null
        if (canvas && typeof canvas.getContext === 'function') {
          tryRender(canvas)
          return
        }

        // 其次尝试 document 查询
        if (typeof document !== 'undefined') {
          canvas = document.getElementById('qr')
          if (canvas && typeof canvas.getContext === 'function') {
            tryRender(canvas)
            return
          }
        }

        // 最后使用 uni 选择器（H5 也可拿到 node）
        try {
          uni.createSelectorQuery()
            .select('#qr')
            .node(res => {
              if (res && res.node && typeof res.node.getContext === 'function') {
                tryRender(res.node)
              } else {
                uni.showToast({ title: '画布不存在', icon: 'none' })
              }
            })
            .exec()
        } catch (e) {
          uni.showToast({ title: '画布不存在', icon: 'none' })
        }
      })
      /* #endif */
    },
  },
}
</script>

<style>
.tool-wrap { display: grid; gap: 16rpx; }
.ipt {
  height: 64rpx; border-radius: 20rpx; padding: 0 20rpx; color: #e9ecff;
  background: rgba(255,255,255,.06); border: 2rpx solid rgba(255,255,255,.12);
}
.ph { color: #a7b0d9; }
.btn { height: 60rpx; border-radius: 20rpx; border: 2rpx solid rgba(255,255,255,.12); background: rgba(255,255,255,.06); color: #e9ecff; font-size: 24rpx; }
.btn.primary { background: linear-gradient(135deg, #6c8cff, #5a6dff); border-color: rgba(0,0,0,.2); }
.canvas { background: #ffffff; border-radius: 16rpx; margin-top: 10rpx; max-width: 100%; }
.hint { color: #a7b0d9; font-size: 22rpx; }
</style>


